#!/bin/bash
# Author : Raman Rawat
# Usage
# Generate DejaVu TDD file from Catalog.osm file
# ./GenCatalogTDDFromOSM.sh osmFile LateType
# osmFile == OSM file of the catalog
# LateType == LateType to searcg in the osm file

# global variable - to holds start & end line numbers of "feature { ... }" content in .osm file
declare -a array1

# A function can only return an int - hence global array is used.
MakeArray()
{

counter=-1
for lt in $1
do
     let counter=counter+1    # let is MUCH MUCH faster than expr !!!!!!!!!!
     
     array1[$counter]=$lt
     #echo "Line" $counter ": "${array1[counter]}
done

#echo "Size of array = " ${#array1[*]}
}

#catalog=$1
catalog=$1			# OSM file of the catalog
featureLateType=$2 # The late type in catalog for which the tdd is to be generated
modifiedCatalog=Modified$catalog

# Check if the asked for lateType is in OSM File
#lateType=`awk '/feature $featureLateType/ ' $catalog`
#if [ $lateType ]
#then
#echo $lateType
#echo $featureLateType " not found in "$catalog
#exit 1
#fi

# input OSM file cannot be parsed as it is. 
# Change the input .osm file to have only feature text between {}
awk '/feature/,/}/ { print $0}' $catalog > $modifiedCatalog

# Array of LateTypes in catalog - all lines have "feature"
lateType=`awk '/feature/ { print $2 }' $modifiedCatalog`

#echo "LateTypes read from catalog "$lateType

#echo ${#array1[*]}

# find the lines numbers matching { and }
lateTypeLineNum=`awk '/{/,/}/p { print NR}' $modifiedCatalog`

#echo $lateTypeLineNum

MakeArray "$lateTypeLineNum"

# Add the last line number containing the ending "}"
lastLine=`wc -l $modifiedCatalog  | awk '{ print $1 }'`
let lastLine=lastLine+1     

nArraySize=${#array1[*]}
#let nArraySize=nArraySize+1    # let is MUCH MUCH faster than expr !!!!!!!!!!
array1[$nArraySize]=$lastLine

#echo "Line numbers" ${array1[@]}

i=0
j=0
#for ((i=0 ; i < ${#array1[*]}-1; i+=1))
for lt in $lateType
do 
     let j=i+1

	 let startLine=${array1[i]}
	 let  endLine=${array1[j]}-1

    #echo "Start Line Num " $startLine " End Line Num " ${endLine} "for "$lt

	#awk ' { if(NR > 1 && NR < 4) print $0}' $modifiedCatalog
	
	#awk -v start="${startLine}" -v end="${endLine}"   ' { if(NR > start && NR < end) print "name:"$2",  type:"$1 }'  $modifiedCatalog
	
	if [ "$lt" == "$featureLateType" ] ; then
		awk -v start="${startLine}" -v end="${endLine}" -f GenTemplFromOSM.awk $modifiedCatalog 
	fi
	
	#> $lt.tdd
	#cat $lt.tdd
	
    let i=i+1

    #echo "Line" $counter ": "${array1[counter]}
done

